import { message } from 'antd';
import { DynamicObjectAny } from '@/typings';
import { DataField } from '@formily/core/esm/types';
import { Form } from '@formily/core/esm/models';
import { xhrGet } from '@/services';
import { getUserInfo } from '@/utils/userInfo';
const REJECT_PARAMS = ['createUser, createTime', 'status'];

let confirmTime: number = 0;
export const confirm = async (pageId: string) => {
  if (!pageId) {
    message.warn(`pageId不能为空`);
    return;
  }
  if (confirmTime >= 3) {
    confirmTime = 0;
    return;
  }
  confirmTime++;
  try {
    const { success }: any = await xhrGet(`/afm/attachment/confirm`, { pageId });
    if (!success) {
      throw new Error('error');
    } else {
      confirmTime = 0;
    }

    return;
  } catch (e) {
    await confirm(pageId);
  }
};

export const transformRejectParams = (params: DynamicObjectAny): DynamicObjectAny => {
  const newParams: DynamicObjectAny = {};

  Object.keys(params || {}).forEach((key) => {
    if (!REJECT_PARAMS.includes(key)) {
      newParams[key] = params[key];
    }
  });

  return newParams;
};

// 公共操作方法
export const commomStateUse = {
  /**
   *
   * @param state 字段
   * @returns 获取 onChange 中所有参数
   */

  getChangedValues: (state: DataField) => {
    try {
      const key = state?.props?.name;
      return state?.query(`.${key}`)?.getIn()?.inputValues;
    } catch (err) {
      throw 'getChangedValues，获取onChange参数报错!';
    }
  },
  getFiledProps: (state: DataField) => {
    try {
      const key = state?.props?.name;
      return state?.query(`.${key}`)?.getIn()?.props?.component[1];
    } catch (err) {
      throw 'getFiledProps,属性报错!';
    }
  },
  getFiledValue: ({
    key,
    form,
    callBack,
  }: {
    key: string;
    form: Form;
    callBack: (val: string) => any;
  }) => {
    form.getFieldState(key, (state) => {
      callBack(state.value);
    });
  },
};

/**
 * @description 赋值给借款人
 * @param form 实例
 * @param key 赋值对象
 */
export const setDefaultUser = (form: Form, key: string) => {
  const value = getUserInfo().userCode;
  form.getFieldState(key, (state) => {
    state.value = value;
  });
};
/**
 * @description 设置 select 组件初始化数据
 * @param form 实例
 * @param key 赋值对象
 */
export const setSelectInitialValue = (form: Form, key: string) => {
  form.getFieldState(key, (st) => {
    if (st.componentProps?.initDefaultValue !== true) {
      st.componentProps = {
        ...st.componentProps,
        initDefaultValue: true,
      };
    }
  });
};
/**
 *
 * @param form
 * @returns 处理基础属性的方法
 */
export const dealProps = (form: Form) => {
  return (key: string, propsKey: string, value: any) => {
    form.getFieldState(key, (st) => {
      if (typeof st[propsKey] === 'object' && typeof value === 'object') {
        if (Array.isArray(st[propsKey]) || Array.isArray(value)) {
          st[propsKey] = value || [];
        } else {
          st[propsKey] = {
            ...st[propsKey],
            ...value,
          };
        }
      } else {
        st[propsKey] = value;
      }
    });
  };
};

/**
 *
 */

enum BANK_ACCT_TYPE {
  SUPPLIER = 'Supplier',
  PERSONNEL = 'Personnel',
  CUSTOMER = 'Customer',
  COMPANY = "Company"
}

export const getParamsBackFromTypes = (form: any, type: string, pageType: string, cbk?: (data: any, form: any) => any) => {
  // 需要客户编码的场景 type
  const depsParams: any = form.values;
  if (cbk) {
    const a = cbk(depsParams, form);
    return a;
  }
  const pageParams = {
    code: '',
    pageCode: 'BankAcct_List',
    bankAcctType: ''
  };
  if (['ExpRbrs_01'].includes(type)) {
    pageParams.bankAcctType = depsParams.pymtType === 'PB' ? 'Supplier' : 'Personnel'
    const nameKey = form?.getValuesIn('beneficiary');
    pageParams.code = depsParams.pymtType === 'PB' ? depsParams['supplier'] : depsParams[nameKey];
  }
  // fiori
  if (['HQKSJB_07', 'YGZQ_01'].includes(type)) {
    console.log(pageParams);
    pageParams.bankAcctType = 'Personnel'
    pageParams.code = depsParams.employeeId;
  }
  if (['YFKTK_03'].includes(type)) {
    pageParams.bankAcctType = 'Supplier';
    pageParams.code = depsParams.supplierCode;
  }

  if (['GCGL_01', 'GCGL_02'].includes(type)) {
    pageParams.bankAcctType = BANK_ACCT_TYPE.SUPPLIER;
    pageParams.code = depsParams.supplierCode;
  } else if (['YFKTK_02'].includes(type)) {
    pageParams.bankAcctType = BANK_ACCT_TYPE.COMPANY;
    pageParams.code = depsParams.cllctCoCode;
  }
  if (['BizTravelRbrs',
    'BizCarRbrs',
    'EncourageRbrs',
    'TreatRbrs',
    'OtherRbrs',
    'PayRbrs',
    'ShippingRbrs',
    'BizInterCoRbrs'].includes(pageType)) {
    pageParams.bankAcctType = depsParams.pymtType === 'PB' ? 'Supplier' : 'Personnel'
    const nameKey = form?.getValuesIn('beneficiary');
    pageParams.code = depsParams.pymtType === 'PB' ? depsParams['supplier'] : depsParams[nameKey];
  }
  // 下面用来除自己的银行账号
  return pageParams;
};

// 动态设置下拉值
export const getPymtTypeValue = (form: any, data: any[], type: string, cbk?: (data: any) => any) => {
  if (cbk) {
    return cbk(data);
  }
  const depsParams: any = form.values;
  let pym = [];
  if (['ExpRbrs_01'].includes(type)) {
    pym = depsParams.pymtType === 'PB' ? data.concat(['URI']) : data
  }
  if(['HQKSJB_07'].includes(type)){
    pym = depsParams.employeeId ? data.filter(item => item === 'BANK') : data.filter(item => item === 'FREE');
  }
  if (!pym.length) {
    return data
  }
  return pym
}


export const pymtTypeDef = (form: any, type: string, pageType: string) => {
  const depsParams: any = form.values;
  let pym = true;
  if (['ExpRbrs_01'].includes(type)) {
    pym = depsParams.pymtType !== 'PR' ? false : true;
  }
  if (['BizTravelRbrs',
    'BizCarRbrs',
    'EncourageRbrs',
    'TreatRbrs',
    'OtherRbrs',
    'PayRbrs',
    'ShippingRbrs',
    'BizInterCoRbrs'].includes(pageType)) {
    pym = depsParams.pymtType !== 'PR' ? false : true;
  }
  return pym
}
